<template>
  <div class="profile-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">
            <el-icon class="title-icon"><User /></el-icon>
            个人资料
          </h1>
          <p class="page-subtitle">管理您的个人信息和账户设置</p>
        </div>
      </div>
    </div>

    <div class="profile-content">
      <div class="content-grid">
        <!-- 左侧个人信息卡片 -->
        <div class="profile-card">
          <div class="avatar-section">
            <div class="avatar-container">
              <el-avatar
                :size="120"
                :src="userInfo.avatar"
                class="user-avatar"
              >
                <el-icon><User /></el-icon>
              </el-avatar>
              <div class="avatar-overlay" @click="showAvatarDialog = true">
                <el-icon><Camera /></el-icon>
                <span>更换头像</span>
              </div>
            </div>
            <div class="user-basic-info">
              <h3 class="user-name">{{ userInfo.name }}</h3>
              <p class="user-id">学号: {{ userInfo.studentId }}</p>
              <p class="user-major">{{ userInfo.major }}</p>
              <el-tag :type="userInfo.status === 'active' ? 'success' : 'warning'" size="small">
                {{ userInfo.status === 'active' ? '正常' : '待激活' }}
              </el-tag>
            </div>
          </div>

          <div class="stats-section">
            <div class="stat-item">
              <div class="stat-value">{{ userStats.totalExams }}</div>
              <div class="stat-label">参与考试</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ userStats.averageScore }}%</div>
              <div class="stat-label">平均分</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ userStats.rank }}</div>
              <div class="stat-label">班级排名</div>
            </div>
          </div>
        </div>

        <!-- 右侧表单区域 -->
        <div class="form-section">
          <el-tabs v-model="activeTab" class="profile-tabs">
            <!-- 基本信息 -->
            <el-tab-pane label="基本信息" name="basic">
              <el-form
                ref="basicFormRef"
                :model="basicForm"
                :rules="basicRules"
                label-width="100px"
                class="profile-form"
              >
                <el-form-item label="姓名" prop="realname">
                  <el-input
                    v-model="basicForm.realname"
                    placeholder="请输入姓名"
                    :disabled="!editMode.basic"
                  />
                </el-form-item>
                <el-form-item label="学号">
                  <el-input
                    :value="userInfo.studentId"
                    placeholder="学号"
                    disabled
                  />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input
                    v-model="basicForm.email"
                    placeholder="请输入邮箱"
                    :disabled="!editMode.basic"
                  />
                </el-form-item>
                <el-form-item label="密码" prop="password" v-if="editMode.basic">
                  <el-input
                    v-model="basicForm.password"
                    type="password"
                    placeholder="如需修改密码请输入新密码，否则留空"
                    show-password
                  />
                </el-form-item>
                <el-form-item>
                  <div class="form-actions">
                    <el-button
                      v-if="!editMode.basic"
                      type="primary"
                      @click="toggleEdit('basic')"
                    >
                      <el-icon><Edit /></el-icon>
                      编辑信息
                    </el-button>
                    <template v-else>
                      <el-button @click="cancelEdit('basic')">
                        取消
                      </el-button>
                      <el-button
                        type="primary"
                        :loading="saving.basic"
                        @click="saveBasicInfo"
                      >
                        保存
                      </el-button>
                    </template>
                  </div>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <!-- 安全设置 -->
            <el-tab-pane label="安全设置" name="security">
              <div class="security-section">
                <!-- 密码修改 -->
                <div class="security-item">
                  <div class="security-header">
                    <h4>修改密码</h4>
                    <p>定期更换密码，保护账户安全</p>
                  </div>
                  <el-button
                    type="primary"
                    @click="showPasswordDialog = true"
                  >
                    修改密码
                  </el-button>
                </div>

                <!-- 登录设备 -->
                <div class="security-item">
                  <div class="security-header">
                    <h4>登录设备</h4>
                    <p>管理您的登录设备</p>
                  </div>
                  <el-button @click="showDevicesDialog = true">
                    查看设备
                  </el-button>
                </div>

                <!-- 账户状态 -->
                <div class="security-item">
                  <div class="security-header">
                    <h4>账户状态</h4>
                    <p>当前账户状态: 
                      <el-tag :type="userInfo.status === 'active' ? 'success' : 'warning'" size="small">
                        {{ userInfo.status === 'active' ? '正常' : '待激活' }}
                      </el-tag>
                    </p>
                  </div>
                  <div class="status-info">
                    <p>上次登录: {{ formatDateTime(userInfo.lastLogin) }}</p>
                    <p>注册时间: {{ formatDateTime(userInfo.createdAt) }}</p>
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <!-- 通知设置 -->
            <el-tab-pane label="通知设置" name="notification">
              <el-form
                ref="notificationFormRef"
                :model="notificationForm"
                label-width="150px"
                class="notification-form"
              >
                <el-form-item label="考试通知">
                  <el-switch
                    v-model="notificationForm.examNotification"
                    active-text="开启"
                    inactive-text="关闭"
                  />
                  <p class="form-help">接收考试开始、结束等重要通知</p>
                </el-form-item>
                <el-form-item label="成绩通知">
                  <el-switch
                    v-model="notificationForm.scoreNotification"
                    active-text="开启"
                    inactive-text="关闭"
                  />
                  <p class="form-help">考试成绩公布时接收通知</p>
                </el-form-item>
                <el-form-item label="系统消息">
                  <el-switch
                    v-model="notificationForm.systemNotification"
                    active-text="开启"
                    inactive-text="关闭"
                  />
                  <p class="form-help">接收系统维护、更新等消息</p>
                </el-form-item>
                <el-form-item label="邮件通知">
                  <el-switch
                    v-model="notificationForm.emailNotification"
                    active-text="开启"
                    inactive-text="关闭"
                  />
                  <p class="form-help">通过邮件接收重要通知</p>
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    :loading="saving.notification"
                    @click="saveNotificationSettings"
                  >
                    保存设置
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>

    <!-- 头像上传对话框 -->
    <el-dialog
      v-model="showAvatarDialog"
      title="更换头像"
      width="400px"
    >
      <div class="avatar-upload">
        <el-upload
          class="avatar-uploader"
          action="#"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="uploadAvatar"
        >
          <img v-if="previewAvatar" :src="previewAvatar" class="avatar-preview" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="upload-tips">
          <p>支持 JPG、PNG 格式</p>
          <p>文件大小不超过 2MB</p>
          <p>建议尺寸 200x200 像素</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="showAvatarDialog = false">取消</el-button>
        <el-button
          type="primary"
          :loading="uploading"
          :disabled="!previewAvatar"
          @click="confirmAvatar"
        >
          确认更换
        </el-button>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="showPasswordDialog"
      title="修改密码"
      width="400px"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input
            v-model="passwordForm.currentPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button
          type="primary"
          :loading="saving.password"
          @click="changePassword"
        >
          确认修改
        </el-button>
      </template>
    </el-dialog>

    <!-- 登录设备对话框 -->
    <el-dialog
      v-model="showDevicesDialog"
      title="登录设备"
      width="600px"
    >
      <div class="devices-list">
        <div
          v-for="device in loginDevices"
          :key="device.id"
          class="device-item"
        >
          <div class="device-info">
            <div class="device-icon">
              <el-icon><Monitor /></el-icon>
            </div>
            <div class="device-details">
              <h4>{{ device.deviceName }}</h4>
              <p>{{ device.browser }} · {{ device.os }}</p>
              <p class="device-location">{{ device.location }}</p>
              <p class="device-time">最后活动: {{ formatDateTime(device.lastActive) }}</p>
            </div>
          </div>
          <div class="device-actions">
            <el-tag v-if="device.isCurrent" type="success" size="small">
              当前设备
            </el-tag>
            <el-button
              v-else
              size="small"
              type="danger"
              text
              @click="removeDevice(device.id)"
            >
              移除
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Camera, Edit, Plus, Monitor } from '@element-plus/icons-vue'
import { getUserInfo, updateUser } from '@/api/auth/login'
import { useUserStore } from '@/stores/user'
// import { changePassword as changePasswordApi } from '@/api/auth/login' // 暂时注释，后端未实现对应接口

// 响应式数据
const userStore = useUserStore()
const activeTab = ref('basic')
const showAvatarDialog = ref(false)
const showPasswordDialog = ref(false)
const showDevicesDialog = ref(false)
const previewAvatar = ref('')
const uploading = ref(false)

const editMode = reactive({
  basic: false
})

const saving = reactive({
  basic: false,
  password: false,
  notification: false
})

// 从用户store中获取用户信息
const userInfo = computed(() => ({
  name: userStore.userInfo?.realName || userStore.userInfo?.username || '未设置',
  studentId: userStore.userInfo?.username || '未设置',
  avatar: userStore.userInfo?.avatar || 'https://design.gemcoder.com/staticResource/echoAiSystemImages/a29fffba1a000df22d9ecfd2b7745047.png',
  email: userStore.userInfo?.email || '',
  major: '计算机科学与技术',
  status: 'active',
  lastLogin: '2024-01-15T10:30:00',
  createdAt: '2023-09-01T08:00:00'
}))

const userStats = ref({
  totalExams: 15,
  averageScore: 85,
  rank: 3
})

const basicForm = reactive({
  realname: '',
  email: '',
  password: ''
})

const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const notificationForm = reactive({
  examNotification: true,
  scoreNotification: true,
  systemNotification: false,
  emailNotification: true
})

const loginDevices = ref([
  {
    id: 1,
    deviceName: 'Windows PC',
    browser: 'Chrome 120.0',
    os: 'Windows 11',
    location: '北京市',
    lastActive: '2024-01-15T10:30:00',
    isCurrent: true
  },
  {
    id: 2,
    deviceName: 'iPhone 15',
    browser: 'Safari 17.0',
    os: 'iOS 17.2',
    location: '北京市',
    lastActive: '2024-01-14T18:20:00',
    isCurrent: false
  }
])

// 表单验证规则
const basicRules = {
  realname: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 方法
const loadUserInfo = async () => {
  try {
    // 从用户store中获取用户信息，填充表单
    if (userStore.userInfo) {
      basicForm.realname = userStore.userInfo.realName || ''
      basicForm.email = userStore.userInfo.email || ''
      basicForm.password = '' // 密码字段留空
    }
  } catch (error) {
    console.error('加载用户信息失败:', error)
    ElMessage.error('加载用户信息失败')
  }
}

const toggleEdit = (type) => {
  editMode[type] = true
}

const cancelEdit = (type) => {
  editMode[type] = false
  // 重置表单数据
  if (type === 'basic') {
    loadUserInfo()
  }
}

const saveBasicInfo = async () => {
  try {
    saving.basic = true
    
    // 调用更新用户信息API
    const response = await updateUser(basicForm)
    if (response.code === 200) {
      // 更新用户store中的信息
      if (userStore.userInfo) {
        userStore.userInfo.realName = basicForm.realname
        userStore.userInfo.email = basicForm.email
      }
      editMode.basic = false
      ElMessage.success(response.message || '基本信息保存成功')
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存基本信息失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    saving.basic = false
  }
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

const uploadAvatar = (options) => {
  const file = options.file
  const reader = new FileReader()
  reader.onload = (e) => {
    previewAvatar.value = e.target.result
  }
  reader.readAsDataURL(file)
}

const confirmAvatar = async () => {
  try {
    uploading.value = true
    // TODO: 调用头像上传API
    // const formData = new FormData()
    // formData.append('avatar', avatarFile)
    // const response = await uploadAvatar(formData)
    // if (response.code === 0) {
    //   userInfo.value.avatar = response.data.avatarUrl
    //   showAvatarDialog.value = false
    //   previewAvatar.value = ''
    //   ElMessage.success('头像更换成功')
    // } else {
    //   ElMessage.error(response.message || '头像上传失败')
    // }
    
    // 临时实现：直接使用预览图片
    userInfo.value.avatar = previewAvatar.value
    showAvatarDialog.value = false
    previewAvatar.value = ''
    ElMessage.success('头像更换成功')
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  } finally {
    uploading.value = false
  }
}

const changePassword = async () => {
  try {
    saving.password = true
    
    // TODO: 调用修改密码API
    // const response = await changePasswordApi(passwordForm)
    // if (response.code === 0) {
    //   showPasswordDialog.value = false
    //   Object.assign(passwordForm, {
    //     currentPassword: '',
    //     newPassword: '',
    //     confirmPassword: ''
    //   })
    //   ElMessage.success('密码修改成功')
    // } else {
    //   ElMessage.error(response.message || '密码修改失败')
    // }
    
    // 临时提示：后端未实现修改密码接口
    ElMessage.warning('修改密码功能暂未实现，请联系管理员')
    showPasswordDialog.value = false
  } catch (error) {
    console.error('密码修改失败:', error)
    ElMessage.error(error.message || '密码修改失败')
  } finally {
    saving.password = false
  }
}

const saveNotificationSettings = async () => {
  try {
    saving.notification = true
    // TODO: 调用保存通知设置API
    // const response = await saveNotificationSettingsApi(notificationSettings.value)
    // if (response.code === 0) {
    //   ElMessage.success('通知设置保存成功')
    // } else {
    //   ElMessage.error(response.message || '保存失败')
    // }
    
    // 临时实现：直接提示成功
    ElMessage.success('通知设置保存成功')
  } catch (error) {
    console.error('保存通知设置失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    saving.notification = false
  }
}

const removeDevice = async (deviceId) => {
  try {
    await ElMessageBox.confirm(
      '确定要移除此设备吗？移除后该设备将需要重新登录。',
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // TODO: 调用移除设备API
    // const response = await removeDeviceApi(deviceId)
    // if (response.code === 0) {
    //   loginDevices.value = loginDevices.value.filter(device => device.id !== deviceId)
    //   ElMessage.success('设备移除成功')
    // } else {
    //   ElMessage.error(response.message || '移除设备失败')
    // }
    
    // 临时实现：直接从本地数据中移除
    loginDevices.value = loginDevices.value.filter(device => device.id !== deviceId)
    ElMessage.success('设备移除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除设备失败:', error)
      ElMessage.error('移除设备失败')
    }
  }
}

const formatDateTime = (date) => {
  return new Date(date).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
.profile-page {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.page-header {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  flex: 1;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 600;
  color: #1d2129;
  margin: 0 0 8px 0;
}

.title-icon {
  margin-right: 12px;
  color: #165dff;
}

.page-subtitle {
  color: #86909c;
  margin: 0;
}

.profile-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.content-grid {
  display: grid;
  grid-template-columns: 300px 1fr;
  min-height: 600px;
}

.profile-card {
  background: #f8f9fa;
  padding: 24px;
  border-right: 1px solid #e5e6eb;
}

.avatar-section {
  text-align: center;
  margin-bottom: 24px;
}

.avatar-container {
  position: relative;
  display: inline-block;
  margin-bottom: 16px;
}

.user-avatar {
  border: 4px solid white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s ease;
  cursor: pointer;
  font-size: 12px;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.user-basic-info {
  margin-bottom: 24px;
}

.user-name {
  font-size: 20px;
  font-weight: 600;
  color: #1d2129;
  margin: 0 0 8px 0;
}

.user-id,
.user-major {
  color: #86909c;
  margin: 4px 0;
}

.stats-section {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #165dff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #86909c;
}

.form-section {
  padding: 24px;
}

.profile-tabs {
  height: 100%;
}

.profile-form {
  max-width: 500px;
}

.form-actions {
  display: flex;
  gap: 12px;
}

.form-help {
  font-size: 12px;
  color: #86909c;
  margin: 4px 0 0 0;
}

.security-section {
  max-width: 600px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.security-item:last-child {
  border-bottom: none;
}

.security-header h4 {
  margin: 0 0 4px 0;
  color: #1d2129;
}

.security-header p {
  margin: 0;
  color: #86909c;
  font-size: 14px;
}

.status-info p {
  margin: 4px 0;
  font-size: 12px;
  color: #86909c;
}

.notification-form {
  max-width: 500px;
}

.avatar-upload {
  text-align: center;
}

.avatar-uploader {
  display: inline-block;
  margin-bottom: 16px;
}

.avatar-preview {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e5e6eb;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  border: 2px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.avatar-uploader-icon:hover {
  border-color: #165dff;
  color: #165dff;
}

.upload-tips {
  color: #86909c;
  font-size: 12px;
}

.upload-tips p {
  margin: 4px 0;
}

.devices-list {
  max-height: 400px;
  overflow-y: auto;
}

.device-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.device-item:last-child {
  border-bottom: none;
}

.device-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.device-icon {
  width: 40px;
  height: 40px;
  background: #f5f7fa;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #165dff;
}

.device-details h4 {
  margin: 0 0 4px 0;
  color: #1d2129;
  font-size: 14px;
}

.device-details p {
  margin: 2px 0;
  font-size: 12px;
  color: #86909c;
}

.device-location {
  color: #4e5969 !important;
}

.device-actions {
  display: flex;
  align-items: center;
}

@media (max-width: 768px) {
  .profile-page {
    padding: 16px;
  }
  
  .content-grid {
    grid-template-columns: 1fr;
  }
  
  .profile-card {
    border-right: none;
    border-bottom: 1px solid #e5e6eb;
  }
  
  .stats-section {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .security-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .device-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>